<template>
  <div class="container">
    <div class="edit-table-toolbar">
      <div class="edit-table-toolbar__title">{{ title }}</div>
      <div class="edit-btn" v-if="!hideBtn">
        <el-button
          size="mini"
          icon="el-icon-circle-plus-outline"
          @click="add"
          >新增</el-button
        >
        <el-button
          size="mini"
          icon="el-icon-edit-outline"
          @click="edit"
          >编辑</el-button
        >
      </div>
    </div>
    <el-table
      :data="tableData"
      row-key="id"
      border
      ref="editTbale"
      :row-class-name="tableRowClassName"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="sort" width="80" label="序号" align="center">
        <template slot-scope="scope">
          <span class="index">{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="context" label="*作业内容" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.edit && isEditTable"
            size="mini"
            type="textarea"
            :autosize="true"
            maxlength="256"
            show-word-limit
            placeholder="请输入"
            @change="handleMenuClick(scope.row)"
            v-model="scope.row.context"
          ></el-input>
          <span v-else>{{ scope.row.context }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="contextStandard" label="作业标准" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="
              scope.row.edit &&
              isEditTable &&
              (stepLevel == 1 || (stepLevel == 2 && !scope.row.children))
            "
            size="mini"
            type="textarea"
            :autosize="true"
            maxlength="256"
            show-word-limit
            placeholder="请输入"
            @change="handleMenuClick(scope.row)"
            v-model="scope.row.contextStandard"
          ></el-input>
          <span v-else>{{ scope.row.contextStandard }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="risk" label="作业风险&控制措施" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="
              scope.row.edit &&
              isEditTable &&
              (stepLevel == 1 || (stepLevel == 2 && !scope.row.children))
            "
            size="mini"
            placeholder="请输入"
            @change="handleMenuClick(scope.row)"
            v-model="scope.row.risk"
            readonly
          >
            <el-button
              slot="append"
              type="text"
              icon="el-icon-s-ticket"
              @click="inputRiskData(scope.$index, scope.row)"
            ></el-button
          ></el-input>
          <span v-else>{{ scope.row.risk }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="itemParamString" label="数据记录项" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="
              scope.row.edit &&
              isEditTable &&
              (stepLevel == 1 || (stepLevel == 2 && !scope.row.children))
            "
            size="mini"
            placeholder="请点击"
            @change="handleMenuClick(scope.row)"
            v-model="scope.row.itemParamString"
            readonly
          >
            <el-button
              slot="append"
              type="text"
              icon="el-icon-s-fold"
              @click="inputDataItem(scope.$index, scope.row)"
            ></el-button>
          </el-input>
          <span v-else>{{ scope.row.itemParamString }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="验收级别" align="center">
        <template slot-scope="scope">
          <el-select
            v-if="
              scope.row.edit &&
              isEditTable &&
              (stepLevel == 1 || (stepLevel == 2 && !scope.row.children))
            "
            size="mini"
            placeholder="请选择"
            @change="(value) => handleSelectChange(value, scope.row)"
            v-model="scope.row.level"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <span v-else>{{ scope.row.levelabel }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        width="200"
        label="操作"
        align="center"
        v-if="!hideBtn"
      >
        <template slot-scope="scope">
          <template v-if="scope.row.children">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRow(scope.row, scope.$index)"
            ></el-button
            >
            <el-button
              type="text"
              size="mini"
              v-if="stepLevel == 2"
              icon="el-icon-plus"
              @click="addChildren(scope.row, scope.$index)"
            ></el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-top"
              @click="moveUp(scope.row, scope.$index)"
            ></el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-bottom"
              @click="moveDown(scope.row, scope.$index)"
            ></el-button
            >
          </template>
          <template v-else>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-delete"
              @click="deleteChildRow(scope.row, scope.$index)"
            ></el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-top"
              @click="childMoveUp(scope.row, scope.$index)"
            ></el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-bottom"
              @click="childMoveDown(scope.row, scope.$index)"
            ></el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <dialogPublic
      :title="DataItemTitle"
      :show.sync="show"
      v-if="show"
      @doSubmit="doSubmit"
      @doClose="doClose"
    >
      <inputForm :paramsList="currentList" ref="inputForm" />
    </dialogPublic>
    <dialogPublic
      title="作业风险库"
      :show.sync="showRisk"
      v-if="showRisk"
      :fullscreen="true"
      @doSubmit="selectRisk"
      @doClose="() => (showRisk = false)"
    >
      <operateRisk pageType="detail" ref="operateRisk"></operateRisk>
    </dialogPublic>
  </div>
</template>

<script>
import inputForm from "./inputForm.vue";
import operateRisk from "../../operateRiskLibrary/index.vue";
export default {
  props: {
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
    isEditTable: {
      type: Boolean,
      default: true,
    },
    hideBtn: {
      type: Boolean,
      default: false,
    },
    stepLevel: {
      type: Number,
    },
  },
  components: {
    inputForm,
    operateRisk,
  },
  data() {
    return {
      //弹框
      show: false,
      showRisk: false,
      DataItemTitle: "",
      //编辑表格
      title: "作业步骤:",
      tableData: [],
      currentIndex: null,
      currentRow: null,
      options: [
        { label: "Ⅰ", value: 1 },
        { label: "Ⅱ", value: 2 },
        { label: "Ⅲ", value: 3 },
      ],
      select: {
        1: "Ⅰ",
        2: "Ⅱ",
        3: "Ⅲ",
      },
      currentList: [],
    };
  },
  created() {
    this.init(this.data);
  },
  mounted() {},
  watch: {
    data: {
      handler(val) {
        this.tableData = val;
      },
      deep: true,
    },
  },
  methods: {
    init(data) {
      //this.$set(this.tableData,this.data)
      data.forEach((item, i) => {
        this.tableData.push(item);
      });
    },
    //行样式
    tableRowClassName({ row, rowIndex }) {
      if (row.children) {
        return "checkRow";
      } else {
        return "";
      }
    },
    handleMenuClick(value) {},
    handleSelectChange(val, row) {
      row.level = val;
      row.levelabel = this.select[val];
    },
    //新增一行
    add() {
      const obj = {
        id: this.generateMixed(10),
        context: "",
        contextStandard: "",
        risk: "",
        itemParamString: "",
        itemParams: [],
        level: "",
        levelabel: "",
        edit: true,
        children: [],
      };
      obj.rowIndex = this.tableData.length;
      obj.sort = this.tableData.length + 1;
      this.tableData.push(obj);
    },
    //新建下级
    addChildren(row, index) {
      const obj = {
        id: this.generateMixed(10),
        context: "",
        contextStandard: "",
        risk: "",
        itemParamString: "",
        itemParams: [],
        levelabel: "",
        level: "",
        edit: true,
      };
      obj.sort = `${row.sort}.${row.children.length + 1}`;
      obj.parentId = row.id;
      obj.rowIndex = row.children.length;
      row.children.push(obj);
      setTimeout(() => {
        this.$refs.editTbale.toggleRowExpansion(row, true);
      }, 0);
    },
    //编辑
    edit() {
      this.tableData.forEach((item, i) => {
        item.edit = true;
        if (item.children.length != 0) {
          item.children.forEach((child, index) => {
            child.edit = true;
          });
        }
      });
    },
    //删除一行
    deleteRow(row, index) {
      this.tableData.splice(row.rowIndex, 1);
      this.tableData.forEach((item, index) => {
        item.rowIndex = index;
        item.sort = index + 1;
      });
    },
    //删除下级一行
    deleteChildRow(row, index) {
      let parentIndex = this.getIndex(row.parentId);
      this.tableData[parentIndex].children.splice(row.rowIndex, 1);
      this.tableData[parentIndex].children.forEach((item, index) => {
        item.rowIndex = index;
        item.sort = `${parentIndex + 1}.${index + 1}`;
      });
    },
    //上移
    moveUp(row, index) {
      if (row.rowIndex > 0) {
        let upDate = this.tableData[row.rowIndex - 1];
        this.tableData.splice(row.rowIndex - 1, 1);
        this.tableData.splice(row.rowIndex, 0, upDate);
        this.tableData.forEach((item, i) => {
          item.rowIndex = i;
          item.sort = i + 1;
        });
      } else {
        alert("已经是第一条，不可上移");
      }
    },
    //下移
    moveDown(row, index) {
      if (row.rowIndex + 1 === this.tableData.length) {
        alert("已经是最后一条，不可下移");
      } else {
        let upDate = this.tableData[row.rowIndex + 1];
        // 删除下一条数据
        this.tableData.splice(row.rowIndex + 1, 1);
        // 增添被删除的那一条数据
        this.tableData.splice(row.rowIndex, 0, upDate);
        this.tableData.forEach((item, i) => {
          item.rowIndex = i;
          item.sort = i + 1;
        });
      }
    },
    //上移
    childMoveUp(row, index) {
      let parentIndex = this.getIndex(row.parentId);
      if (row.rowIndex > 0) {
        let upDate = this.tableData[parentIndex].children[row.rowIndex - 1];
        this.tableData[parentIndex].children.splice(row.rowIndex - 1, 1);
        this.tableData[parentIndex].children.splice(row.rowIndex, 0, upDate);
        this.tableData[parentIndex].children.forEach((item, i) => {
          item.rowIndex = i;
          item.sort = `${parentIndex + 1}.${i + 1}`;
        });
      } else {
        alert("已经是第一条，不可上移");
      }
    },
    //下移
    childMoveDown(row, index) {
      let parentIndex = this.getIndex(row.parentId);
      if (row.rowIndex + 1 === this.tableData[parentIndex].children.length) {
        alert("已经是最后一条，不可下移");
      } else {
        let upDate = this.tableData[parentIndex].children[row.rowIndex + 1];
        // 删除下一条数据
        this.tableData[parentIndex].children.splice(row.rowIndex + 1, 1);
        // 增添被删除的那一条数据
        this.tableData[parentIndex].children.splice(row.rowIndex, 0, upDate);
        this.tableData[parentIndex].children.forEach((item, i) => {
          item.rowIndex = i;
          item.sort = `${parentIndex + 1}.${i + 1}`;
        });
      }
    },
    //获取随机字符串
    generateMixed(n) {
      let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = $chars.length;
      let pwd = "";
      for (let i = 0; i < n; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    //获取索引
    getIndex(id) {
      let index;
      this.tableData.forEach((item, i) => {
        if (item.id == id) {
          index = i;
        }
      });
      return index;
    },
    //点击数据记录项
    inputDataItem(index, row) {
      this.currentRow = row;
      this.currentList = row.itemParams;
      this.show = true;
    },
    //提交弹框
    doSubmit() {
      this.currentRow.itemParamString =
        this.$refs.inputForm.customsHandleConfirm();
      this.currentRow.itemParams = this.$refs.inputForm.handleDataList();
      this.doClose();
    },
    //点击风险项
    inputRiskData(index, row) {
      this.currentRow = row;
      this.showRisk = true;
    },
    //提交风险项
    selectRisk() {
      let data = this.$refs.operateRisk.getSelectData();
      this.currentRow.risk = data.map((item) => item.desc).join(";");
      this.showRisk = false;
    },
    //关闭弹框
    doClose() {
      this.show = false;
    },
    clearTableData() {
      this.tableData = [];
    },
    //判断表格必填项
    handleTbaleData(data) {
      let isComplete = true;
      data.forEach((item, i) => {
        item.context == "" && (isComplete = false);
        if (item.children.length != 0) {
          item.children.forEach((child, index) => {
            child.context == "" && (isComplete = false);
          });
        }
      });
      return isComplete;
    },
    //判断步骤层级为2的表格子项是否填写完整
    isTableComplete(data) {
      if (this.stepLevel == 2) {
        return data.every((item) => {
          return item.children.length > 0;
        });
      } else {
        return true;
      }
    },
    //获取表格数据
    getTableData() {
      if (this.tableData.length == 0) {
        this.$message.warning("请至少添加一条作业项目");
      } else if (!this.isTableComplete(this.tableData)) {
        this.$message.warning("作业项目二级项不能为空");
        return false;
      } else if (!this.handleTbaleData(this.tableData)) {
        this.$message.warning("作业内容不能为空");
        return false;
      } else {
        let data = this.tableData.map((item, i) => {
          delete item.id;
          delete item.sort;
          delete item.edit;
          if (item.children.length != 0) {
            item.children.forEach((child, index) => {
              delete child.id;
              delete child.sort;
              delete child.edit;
            });
          }
          return item;
        });
        return data;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  .edit-table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
  }
  .edit-table-toolbar__title {
    font-weight: bold;
    margin-left: 10px;
  }
  .edit-table-toolbar__title::before {
    content: "*";
    color: red;
    margin-right: 4px;
  }
  /deep/.el-table {
    .checkRow {
      background-color: #b8e2f5 !important;
    }
    tbody tr:hover > td {
      background-color: transparent;
    }
  }
}
</style>